package com.bridgetek.carlauncher.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.bridgetek.carlauncher.Constants;
import com.bridgetek.carlauncher.bean.Gps;

import java.util.Timer;
import java.util.TimerTask;


public class LocationService extends Service {
    private Gps mGps;
    private Timer mTimer = new Timer();
    private MyTimerTask myTask;
    private AMapLocation mAMapLocation = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        mGps = new Gps(this);
        myTask = new MyTimerTask();
        mTimer.schedule(myTask, 0, 5000);
    }


    @Override
    public boolean stopService(Intent name) {
        return super.stopService(name);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mGps != null) {
            mGps.closeLocation();
        }
        cancelTimer();
    }


    /***********************************************
     * 高德定位
     *********************************/

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            if (mGps != null) {
                mAMapLocation = mGps.getAMapLocation();
                if (mAMapLocation != null) {
                    Intent intent = new Intent();
                    intent.setAction(Constants.LOCATION_ACTION);
                    intent.putExtra(Constants.CITY_ADCODE, mAMapLocation.getAdCode());
                    sendBroadcast(intent);
                    Log.d("WTF", "run: " + mAMapLocation.getLatitude() + "----" + mAMapLocation.getLongitude());
                    Log.d("WTF", "run: 城市code " + mAMapLocation.getCityCode());
                    Log.d("WTF", "onLocationChanged:定位结果来源 " + mAMapLocation.getLocationType());
                    Log.d("WTF", "onLocationChanged:精度信息 " + mAMapLocation.getAccuracy());
                }
            }
        }
    }

    /**************************************************高德定位**********************************/


    /**
     * 关掉定时器
     */
    private void cancelTimer() {
        if (myTask != null) {
            myTask.cancel();
            myTask = null;
        }
        mTimer.cancel();
        mTimer.purge();
        mTimer = null;
    }
}
